package com.atguigu.mp.jdbc;

import java.sql.*;

/**
 * @author yanglin
 * @create 2024-02-27 13:04 星期二
 * description:
 */
public class JDBCDemo {

    /**
     * 1、加载MySQL 的 JDBC驱动程序
     * 2、建立连接
     * 3、使用PreparedStatement创建查询语句，避免sql注入风险
     * 4、使用PreparedStatement的set方法设置参数
     * 5、处理结果
     * 6、关闭连接
     */
    
    public static void main(String[] args) {
        //第一步：导入MySQL驱动
        Connection conn = null;
        try {
            //1、加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、连接数据库
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hj000?serverTimezone=UTC", "root", "010203");
            System.out.println("连接成功");
            //sql语句
            PreparedStatement preparedStatement = conn.prepareStatement("select * from a");
            //执行sql语句
            ResultSet resultSet = preparedStatement.executeQuery();
            //处理结果
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                System.out.println("id = " + id + "name = " + name + "age = " + age);
            }
//            System.out.println(preparedStatement);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                System.out.println("关闭成功");
            }
        }
    }
    
}
